/*
by txdnet.cn
 */

package txdnet.util;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
 *
 * @author txdnet
 */
public class Context implements ServletContextListener {

    public Context(){}
    
    private static ServletContext sct;
  
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        sct = sce.getServletContext();
        Logger.debug(Context.class, " -- Web Context Initialized . Context Path:".concat(sct.getContextPath()));
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        Logger.debug(Context.class, " -- Web Context Destroyed .");
    }

   public static Object getSessionAttribute(HttpServletRequest request, String name) {
        if(request==null){return null;}
        HttpSession sn = request.getSession(false);
        return (sn != null ? sn.getAttribute(name) : null);
    }

    public static void setSessionAttribute(HttpServletRequest request, String name, Object obj) {
        if(request!=null){
        HttpSession sn = request.getSession(false);
        if(sn==null){
          sn =  request.getSession(true);
        }
        sn.setAttribute(name, obj);
        }
}
 
public static String getRealPath(String path){
     return sct.getRealPath(path);
}

public static ServletContext getServletContext(){
    return sct;
}

public static String getClientIp(HttpServletRequest request){
    String ip = request.getHeader("x-forwarded-for");
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("Proxy-Client-IP");
    }
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getRemoteAddr();
    }
   // if(ip.length()>15)ip=ip.substring(0,15);
    if(ip.indexOf(StaticMark.CHAR_COMMA)>0){
        String[] ipa = ip.split(",");
        for(String v : ipa){
            if(v.indexOf("unknown")<0){
                ip = v ;
                break;
            }
        }
    }
    return ip;
    }
}